package com.distribution.common.web.filter;

import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author test
 * @date 2022年01月03日 22:52
 */

@Component
@Order(0)
public class WebFilter implements Filter {

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", " Origin, X-Requested-With, Content-Type, Accept");

        //在filter中可以修改和添加 header attribute, header 等等
        servletRequest.setAttribute("Good1", "come in filter");

        //由于http servlet request 中的inputStream 只能读取一次, 假如在interceptor中读取过了，则在controller中无法读取body中的内容了，
        //会导致 @RequestBody 绑定异常， 我们可以通过在filter 中RequestWrapper 将inputstream内容复制，防止流内容丢失
        //InputStream is = request.getInputStream();
        //InputStreamReader isr = new InputStreamReader(is);  ---stream 流只能读取一次

        ServletRequest requestWrapper = null;
        if (servletRequest instanceof HttpServletRequest) {
            requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
        }

        //继续执行下一个过滤器
        if (requestWrapper == null) {
            filterChain.doFilter(servletRequest, response);
        } else {
            filterChain.doFilter(requestWrapper, response);
        }

    }

}
